import axios from "axios";
import Config from "../config/";
import Router from "vue-router";
import store from "../store";
import { getToken } from "@/util/auth";

export default {
  showServerError: function(err) {
    try {
      // if( typeof(err.response) == "undefined" ){
      //     window.location.href="/#login";
      //     return;
      // }
      const data = err.response.data;
      console.error("服务器异常【调试信息】: " + data.trace);
      alert(
        "服务器异常:" +
          data.status +
          "\r\n\r\n --------以下为调试信息---------- \r\n" +
          data.message
      );
    } catch (e) {
      console.error(e);
    }
  },

  get: function(url, args) {
    return this.request(url, args, "GET");
  },

  post: function(url, args, cfg) {
    return this.request(url, args, "POST", cfg);
  },

  put: function(url, args) {
    return this.request(url, args, "PUT");
  },

  delete: function(url, args) {
    return this.request(url, args, "DELETE");
  },

  request: function(url, args, method, cfg = {}) {
    if (method.toUpperCase() == "GET") {
      let has = url.indexOf("?") > 0;
      Object.keys(args).forEach(key => {
        if (!has) {
          url += "?" + key + "=" + args[key];
          has = true;
        } else {
          url += "&" + key + "=" + args[key];
        }
      });

      // url += (has?'&':'?') + 'userToken='+apiArgs.userToken+"&ccode="+ccode;
    }
    let config = {
      method: method,
      url: url,
      data: args,
      headers: {
        token: window.localStorage.getItem("usertoken")
      },
      withCredentials: true,
      baseURL: Config.apiUrl + "/",
      ...cfg
    };
    // if (store.getters.token) {
    //   config.headers["token"] = "666"; //getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    return axios(config);
  } // end request
};
